package com.example.softpart.magicAPiCustomFunction;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import com.example.softpart.unil.callMagicAPi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.config.MagicFunction;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.model.MagicEntity;
import org.ssssssss.magicapi.core.model.TreeNode;
import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.ssssssss.magicapi.core.service.MagicResourceService;
import org.ssssssss.script.annotation.Comment;
import org.ssssssss.script.annotation.Function;

import java.util.HashMap;
import java.util.List;

@Component  //注入到Spring容器中
public class accessFunction implements MagicFunction {


    @Autowired
    private JdbcTemplate template;

    @Autowired
    MagicResourceService service;

    /*@Autowired
    private MagicAPIService service;*/

    @Function
    @Comment("获取权限集合")
    public List<String> getPermissionList() {
        // 获取：当前账号所拥有的权限集合
        return StpUtil.getPermissionList();
    }


    @Function
    @Comment("判断是否拥有权限")
    public boolean hasPermission(String access) {
        // 判断：当前账号是否含有指定权限, 返回 true 或 false
        return StpUtil.hasPermission(access);
    }

    @Function
    @Comment("校验是否拥有权限")
    public void checkPermission(String access) {
        // 校验：当前账号是否含有指定权限, 如果验证未通过，则抛出异常: NotPermissionException
        StpUtil.checkPermission("user.add");
    }

    @Function
    @Comment("校验是否拥有以下全部权限")
    public void checkPermissionAnd(String... args) {
        // 校验：当前账号是否含有指定权限 [指定多个，必须全部验证通过]
        StpUtil.checkPermissionAnd( args );
    }

    @Function
    @Comment("更新权限库数据")
    public void updateAccessDB(){
        for (TreeNode<Group> group : service.tree("api").getChildren()) {
            for (MagicEntity api : service.listFiles(group.getNode().getId())) {
                ApiInfo info = (ApiInfo) api;
                DateTime now = DateTime.now();
                try {
                    template.update("replace into access(id, name, method,urls,create_date) values(?,?,?,?,?)",
                            info.getId(),
                            info.getName(),
                            info.getMethod(),
                            group.getNode().getPath() + info.getPath(),
                            now);
                } catch (Exception ignore) {
                    ignore.printStackTrace();
                }
            }
        }
    }

}
